<template>
  <div class="remote-connection-manager">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" size="small" @click="showHostSelector = true">
          <el-icon><Plus /></el-icon>
          新建连接
        </el-button>
        <el-button size="small" @click="toggleSidebar">
          <el-icon><Menu /></el-icon>
          {{ sidebarVisible ? '隐藏' : '显示' }}主机列表
        </el-button>
      </div>
      <div class="toolbar-right">
        <span class="connection-count">活跃连接: {{ activeConnections }}</span>
      </div>
    </div>

    <div class="main-container">
      <!-- 侧边栏 - 主机列表 -->
      <div v-if="sidebarVisible" class="sidebar">
        <div class="sidebar-header">
          <h4>可连接主机</h4>
          <el-input
            v-model="hostSearchQuery"
            placeholder="搜索主机..."
            size="small"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div class="host-list">
          <el-tooltip
            v-for="host in filteredHosts"
            :key="host.id"
            content="双击开启SSH终端，单击激活现有连接"
            placement="top"
          >
            <div
              class="host-item"
              :class="{ 'has-connection': hasActiveConnection(host) }"
              @click="handleHostClick(host)"
              @dblclick="handleHostDoubleClick(host)"
              @contextmenu.prevent="showHostContextMenu($event, host)"
            >
              <div class="host-info">
                <div class="host-name">{{ host.hostname }}</div>
                <div class="host-ip">{{ host.ip_address }}</div>
                <div class="host-status">
                  <el-tag :type="getHostStatusType(host.status)" size="small">
                    {{ getHostStatusText(host.status) }}
                  </el-tag>
                </div>
              </div>
              <div class="host-actions">
                <el-button
                  size="small"
                  type="primary"
                  circle
                  @click.stop="handleHostDoubleClick(host)"
                  title="创建新连接"
                >
                  <el-icon><Connection /></el-icon>
                </el-button>
              </div>
            </div>
          </el-tooltip>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="content-area">
        <!-- 标签栏 -->
        <div class="tab-bar" v-if="tabs.length > 0">
          <draggable
            v-model="tabs"
            class="tab-container"
            item-key="id"
            @end="onTabDragEnd"
          >
            <template #item="{ element: tab }">
              <div
                :class="['tab-item', { active: tab.id === activeTabId }]"
                @click="switchTab(tab.id)"
                @contextmenu.prevent="showTabContextMenu($event, tab)"
              >
                <div class="tab-content">
                  <div class="tab-status">
                    <el-icon :class="getConnectionStatusClass(tab.status)">
                      <component :is="getConnectionStatusIcon(tab.status)" />
                    </el-icon>
                  </div>
                  <div class="tab-info">
                    <div class="tab-title">{{ tab.title }}</div>
                    <div class="tab-subtitle">{{ tab.host.ip_address }}</div>
                  </div>
                  <div class="tab-actions">
                    <el-button
                      size="small"
                      type="text"
                      @click.stop="closeTab(tab.id)"
                    >
                      <el-icon><Close /></el-icon>
                    </el-button>
                  </div>
                </div>
              </div>
            </template>
          </draggable>
        </div>

        <!-- 终端区域 -->
        <div class="terminal-area">
          <div v-if="tabs.length === 0" class="empty-state">
            <el-empty description="暂无连接">
              <el-button type="primary" @click="showHostSelector = true">
                创建新连接
              </el-button>
            </el-empty>
          </div>
          <div
            v-for="tab in tabs"
            :key="tab.id"
            v-show="tab.id === activeTabId"
            class="terminal-container"
          >
            <SSHTerminalTab
              :host="tab.host"
              :tab-id="tab.id"
              @status-change="onTabStatusChange"
              @title-change="onTabTitleChange"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 主机选择对话框 -->
    <el-dialog
      v-model="showHostSelector"
      title="选择要连接的主机"
      width="600px"
    >
      <el-table :data="hosts" @row-dblclick="connectToHostFromDialog">
        <el-table-column prop="hostname" label="主机名" width="150" />
        <el-table-column prop="ip_address" label="IP地址" width="130" />
        <el-table-column prop="host_type_name" label="类型" width="100" />
        <el-table-column prop="environment_name" label="环境" width="100" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getHostStatusType(row.status)" size="small">
              {{ getHostStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              @click="connectToHostFromDialog(row)"
            >
              连接
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 右键菜单 -->
    <div
      v-if="contextMenu.visible"
      class="context-menu"
      :style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }"
    >
      <div class="context-menu-item" @click="handleContextMenuAction('rename')">
        重命名标签
      </div>
      <div class="context-menu-item" @click="handleContextMenuAction('duplicate')">
        复制连接
      </div>
      <div class="context-menu-item" @click="handleContextMenuAction('disconnect')">
        断开连接
      </div>
      <div class="context-menu-divider"></div>
      <div class="context-menu-item" @click="handleContextMenuAction('close')">
        关闭标签
      </div>
      <div class="context-menu-item" @click="handleContextMenuAction('closeOthers')">
        关闭其他标签
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Menu, Search, Connection, Close,
  Link, Loading, CircleClose, CircleCheck
} from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import { cmdbAPI } from '../../api/cmdb'
import SSHTerminalTab from '../../components/SSHTerminalTab.vue'

// 响应式数据
const tabs = ref([])
const activeTabId = ref(null)
const hosts = ref([])
const sidebarVisible = ref(true)
const showHostSelector = ref(false)
const hostSearchQuery = ref('')

// 右键菜单
const contextMenu = reactive({
  visible: false,
  x: 0,
  y: 0,
  target: null
})

// 计算属性
const activeTabs = computed(() => tabs.value.filter(tab => tab.status !== 'closed'))

// 真正的活跃连接数（只统计已连接的SSH会话）
const activeConnections = computed(() =>
  tabs.value.filter(tab => tab.status === 'connected' && tab.sessionId).length
)
const filteredHosts = computed(() => {
  if (!hostSearchQuery.value) return hosts.value
  const query = hostSearchQuery.value.toLowerCase()
  return hosts.value.filter(host =>
    host.hostname.toLowerCase().includes(query) ||
    host.ip_address.includes(query)
  )
})

// 窗口resize处理
let globalResizeTimeout = null
const handleGlobalResize = () => {
  if (globalResizeTimeout) {
    clearTimeout(globalResizeTimeout)
  }

  globalResizeTimeout = setTimeout(() => {
    // 通知所有活跃的终端标签页重新适应尺寸
    tabs.value.forEach(tab => {
      if (tab.status === 'connected') {
        // 这里可以通过ref调用子组件的fitTerminal方法
        // 或者让子组件自己处理resize事件
        console.log(`[RemoteConnectionManager] Triggering resize for tab ${tab.id}`)
      }
    })
  }, 200)
}

// 生命周期
onMounted(async () => {
  await loadHosts()
  loadTabsFromStorage()
  setupKeyboardShortcuts()
  document.addEventListener('click', hideContextMenu)
  window.addEventListener('resize', handleGlobalResize)
})

onUnmounted(() => {
  document.removeEventListener('click', hideContextMenu)
  window.removeEventListener('resize', handleGlobalResize)

  if (globalResizeTimeout) {
    clearTimeout(globalResizeTimeout)
  }

  saveTabsToStorage()
})

// 方法定义
const loadHosts = async () => {
  try {
    const response = await cmdbAPI.getHosts()
    hosts.value = response.results || response
  } catch (error) {
    console.error('加载主机列表失败:', error)
    ElMessage.error('加载主机列表失败')
  }
}

// 单击主机：激活现有连接或显示提示
const handleHostClick = (host) => {
  const existingTabs = tabs.value.filter(tab => tab.host.id === host.id)
  if (existingTabs.length > 0) {
    // 激活最近的标签页
    const latestTab = existingTabs.sort((a, b) =>
      new Date(b.createdAt) - new Date(a.createdAt)
    )[0]
    switchTab(latestTab.id)
    ElMessage.info(`已激活到 ${host.hostname} 的连接`)
  } else {
    ElMessage.info(`双击 ${host.hostname} 创建新的SSH连接`)
  }
}

// 双击主机：创建新标签页（支持同一主机多个连接）
const handleHostDoubleClick = (host) => {
  createNewTab(host)
}

// 创建新标签页
const createNewTab = (host) => {
  const tabId = `tab_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  const existingTabs = tabs.value.filter(tab => tab.host.id === host.id)

  // 生成标签页标题
  const tabTitle = existingTabs.length > 0
    ? `${host.hostname} (${existingTabs.length + 1})`
    : host.hostname

  const newTab = {
    id: tabId,
    title: tabTitle,
    host: host,
    status: 'connecting',
    createdAt: new Date().toISOString(),
    sessionId: null  // SSH会话ID
  }

  tabs.value.push(newTab)
  activeTabId.value = tabId
  showHostSelector.value = false

  ElMessage.success(`正在连接到 ${host.hostname}...`)
}

// 检查主机是否有活跃连接
const hasActiveConnection = (host) => {
  return tabs.value.some(tab =>
    tab.host.id === host.id &&
    (tab.status === 'connected' || tab.status === 'connecting')
  )
}

// 兼容原有的connectToHost方法
const connectToHost = (host) => {
  createNewTab(host)
}

const connectToHostFromDialog = (host) => {
  connectToHost(host)
}

const switchTab = (tabId) => {
  activeTabId.value = tabId
}

const closeTab = async (tabId) => {
  const tabIndex = tabs.value.findIndex(tab => tab.id === tabId)
  if (tabIndex === -1) return

  const tab = tabs.value[tabIndex]

  // 如果标签页正在连接中，询问是否确认关闭
  if (tab.status === 'connected' || tab.status === 'connecting') {
    try {
      await ElMessageBox.confirm(
        `确定要关闭到 ${tab.host.hostname} 的连接吗？`,
        '确认关闭',
        { type: 'warning' }
      )
    } catch {
      return // 用户取消
    }
  }

  // 移除标签页
  tabs.value.splice(tabIndex, 1)

  // 如果关闭的是当前活跃标签，切换到其他标签
  if (activeTabId.value === tabId) {
    if (tabs.value.length > 0) {
      // 优先切换到右边的标签，如果没有则切换到左边
      const newActiveIndex = tabIndex < tabs.value.length ? tabIndex : tabIndex - 1
      activeTabId.value = tabs.value[newActiveIndex]?.id || null
    } else {
      activeTabId.value = null
    }
  }

  saveTabsToStorage()
}

// 关闭其他标签页（只提示一次）
const closeOtherTabs = async (keepTabId) => {
  const otherTabs = tabs.value.filter(t => t.id !== keepTabId)
  if (otherTabs.length === 0) return

  // 检查是否有活跃连接
  const activeOtherTabs = otherTabs.filter(t =>
    t.status === 'connected' || t.status === 'connecting'
  )

  // 如果有活跃连接，只提示一次
  if (activeOtherTabs.length > 0) {
    try {
      await ElMessageBox.confirm(
        `确定要关闭其他 ${otherTabs.length} 个标签页吗？其中 ${activeOtherTabs.length} 个正在连接中。`,
        '确认关闭',
        {
          type: 'warning',
          confirmButtonText: '确定关闭',
          cancelButtonText: '取消'
        }
      )
    } catch {
      return // 用户取消
    }
  }

  // 批量关闭，不再弹出确认对话框
  for (const otherTab of otherTabs) {
    await closeTabSilently(otherTab.id)
  }

  ElMessage.success(`已关闭 ${otherTabs.length} 个标签页`)
}

// 静默关闭标签页（不弹出确认对话框）
const closeTabSilently = async (tabId) => {
  const tabIndex = tabs.value.findIndex(tab => tab.id === tabId)
  if (tabIndex === -1) return

  // 移除标签页
  tabs.value.splice(tabIndex, 1)

  // 如果关闭的是当前活跃标签，切换到其他标签
  if (activeTabId.value === tabId) {
    if (tabs.value.length > 0) {
      // 优先切换到右边的标签，如果没有则切换到左边
      const newActiveIndex = tabIndex < tabs.value.length ? tabIndex : tabIndex - 1
      activeTabId.value = tabs.value[newActiveIndex]?.id || null
    } else {
      activeTabId.value = null
    }
  }

  saveTabsToStorage()
}

const onTabStatusChange = (tabId, status, sessionId = null) => {
  const tab = tabs.value.find(t => t.id === tabId)
  if (tab) {
    tab.status = status

    // 如果连接成功，记录sessionId
    if (status === 'connected' && sessionId) {
      tab.sessionId = sessionId
    }

    // 如果连接断开，清除sessionId
    if (status === 'disconnected' || status === 'error') {
      tab.sessionId = null
    }

    saveTabsToStorage()

    // 输出调试信息
    console.log(`[RemoteConnectionManager] Tab ${tabId} status changed to ${status}`, {
      sessionId,
      activeConnections: activeConnections.value
    })
  }
}

const onTabTitleChange = (tabId, title) => {
  const tab = tabs.value.find(t => t.id === tabId)
  if (tab) {
    tab.title = title
    saveTabsToStorage()
  }
}

const toggleSidebar = () => {
  sidebarVisible.value = !sidebarVisible.value
  localStorage.setItem('remoteConnectionManager.sidebarVisible', sidebarVisible.value)
}



const onTabDragEnd = () => {
  saveTabsToStorage()
}

// 右键菜单相关
const showTabContextMenu = (event, tab) => {
  contextMenu.visible = true
  contextMenu.x = event.clientX
  contextMenu.y = event.clientY
  contextMenu.target = tab
}

const showHostContextMenu = (event, host) => {
  // 主机右键菜单逻辑
  event.preventDefault()
}

const hideContextMenu = () => {
  contextMenu.visible = false
  contextMenu.target = null
}

const handleContextMenuAction = async (action) => {
  const tab = contextMenu.target
  if (!tab) return

  hideContextMenu()

  switch (action) {
    case 'rename':
      await renameTab(tab)
      break
    case 'duplicate':
      connectToHost(tab.host)
      break
    case 'disconnect':
      // 发送断开连接事件
      break
    case 'close':
      closeTab(tab.id)
      break
    case 'closeOthers':
      await closeOtherTabs(tab.id)
      break
  }
}

const renameTab = async (tab) => {
  try {
    const { value: newTitle } = await ElMessageBox.prompt(
      '请输入新的标签名称',
      '重命名标签',
      {
        inputValue: tab.title,
        inputValidator: (value) => {
          if (!value || value.trim() === '') {
            return '标签名称不能为空'
          }
          return true
        }
      }
    )

    if (newTitle && newTitle.trim()) {
      onTabTitleChange(tab.id, newTitle.trim())
    }
  } catch {
    // 用户取消
  }
}

// 键盘快捷键
const setupKeyboardShortcuts = () => {
  document.addEventListener('keydown', (event) => {
    // Ctrl+Tab 切换标签
    if (event.ctrlKey && event.key === 'Tab') {
      event.preventDefault()
      switchToNextTab()
    }

    // Ctrl+W 关闭当前标签
    if (event.ctrlKey && event.key === 'w') {
      event.preventDefault()
      if (activeTabId.value) {
        closeTab(activeTabId.value)
      }
    }

    // Ctrl+T 新建连接
    if (event.ctrlKey && event.key === 't') {
      event.preventDefault()
      showHostSelector.value = true
    }



    // Esc 隐藏右键菜单
    if (event.key === 'Escape') {
      hideContextMenu()
    }
  })
}

const switchToNextTab = () => {
  if (tabs.value.length <= 1) return

  const currentIndex = tabs.value.findIndex(tab => tab.id === activeTabId.value)
  const nextIndex = (currentIndex + 1) % tabs.value.length
  activeTabId.value = tabs.value[nextIndex].id
}

// 状态相关方法
const getHostStatusType = (status) => {
  const types = {
    online: 'success',
    offline: 'info',
    maintenance: 'warning',
    error: 'danger',
    checking: 'warning'
  }
  return types[status] || 'info'
}

const getHostStatusText = (status) => {
  const texts = {
    online: '在线',
    offline: '离线',
    maintenance: '维护中',
    error: '异常',
    checking: '检测中'
  }
  return texts[status] || status
}

const getConnectionStatusClass = (status) => {
  return `status-${status}`
}

const getConnectionStatusIcon = (status) => {
  const icons = {
    connected: CircleCheck,
    connecting: Loading,
    disconnected: CircleClose,
    error: CircleClose
  }
  return icons[status] || CircleClose
}

// 持久化存储
const saveTabsToStorage = () => {
  const tabsData = tabs.value.map(tab => ({
    id: tab.id,
    title: tab.title,
    host: tab.host,
    status: tab.status === 'connected' ? 'disconnected' : tab.status, // 刷新后重置连接状态
    createdAt: tab.createdAt
  }))

  localStorage.setItem('remoteConnectionManager.tabs', JSON.stringify(tabsData))
  localStorage.setItem('remoteConnectionManager.activeTabId', activeTabId.value || '')
}

const loadTabsFromStorage = () => {
  try {
    // 加载侧边栏状态
    const sidebarState = localStorage.getItem('remoteConnectionManager.sidebarVisible')
    if (sidebarState !== null) {
      sidebarVisible.value = sidebarState === 'true'
    }

    // 加载标签页
    const tabsData = localStorage.getItem('remoteConnectionManager.tabs')
    if (tabsData) {
      const parsedTabs = JSON.parse(tabsData)
      tabs.value = parsedTabs.map(tab => ({
        ...tab,
        status: 'disconnected' // 刷新后所有连接都需要重新建立
      }))
    }

    // 加载活跃标签
    const savedActiveTabId = localStorage.getItem('remoteConnectionManager.activeTabId')
    if (savedActiveTabId && tabs.value.find(tab => tab.id === savedActiveTabId)) {
      activeTabId.value = savedActiveTabId
    } else if (tabs.value.length > 0) {
      activeTabId.value = tabs.value[0].id
    }
  } catch (error) {
    console.error('加载标签页状态失败:', error)
  }
}
</script>

<style scoped>
.remote-connection-manager {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  display: flex;
  gap: 8px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.connection-count {
  font-size: 12px;
  color: #606266;
}

.main-container {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.sidebar {
  width: 280px;
  background: white;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.sidebar-header h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #303133;
}

.host-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.host-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 4px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.host-item:hover {
  background: #f0f9ff;
}

.host-info {
  flex: 1;
}

.host-name {
  font-weight: 500;
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
}

.host-ip {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tab-bar {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  overflow-x: auto;
  overflow-y: hidden;
}

.tab-container {
  display: flex;
  min-height: 48px;
}

.tab-item {
  min-width: 200px;
  max-width: 250px;
  border-right: 1px solid #e4e7ed;
  cursor: pointer;
  transition: background-color 0.2s;
}

.tab-item:hover {
  background: #f0f9ff;
}

.tab-item.active {
  background: #e6f7ff;
  border-bottom: 2px solid #409eff;
}

.tab-content {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  height: 100%;
}

.tab-status {
  margin-right: 8px;
}

.tab-info {
  flex: 1;
  min-width: 0;
}

.tab-title {
  font-size: 13px;
  font-weight: 500;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tab-subtitle {
  font-size: 11px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.terminal-area {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.terminal-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: white;
}

.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 9999;
  min-width: 120px;
}

.context-menu-item {
  padding: 8px 16px;
  font-size: 13px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.context-menu-item:hover {
  background: #f0f9ff;
}

.context-menu-divider {
  height: 1px;
  background: #e4e7ed;
  margin: 4px 0;
}

/* 连接状态样式 */
.status-connected {
  color: #67c23a;
}

.status-connecting {
  color: #e6a23c;
  animation: pulse 1.5s infinite;
}

.status-disconnected {
  color: #f56c6c;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* 主机卡片样式优化 */
.host-item {
  cursor: pointer;
  transition: all 0.2s ease;
  border-radius: 4px;
  position: relative;
}

.host-item:hover {
  background: #f0f9ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.host-item.has-connection {
  border-left: 3px solid #67c23a;
  background: #f0f9ff;
}

.host-item.has-connection::after {
  content: '●';
  position: absolute;
  top: 8px;
  right: 8px;
  color: #67c23a;
  font-size: 12px;
}
</style>
